#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DESC_SIZE 256
#define KEY_SIZE 256
#define BUFSIZE 512

#define FNAME "log"
struct node_st
{
	struct node_st *ch[26];
	char desc[DESC_SIZE];
};

int get_word(FILE *fp,char *key,char *desc)
{
	char buf[BUFSIZE];
	char *retp;
	int i,j;
	retp = fgets(buf,BUFSIZE,fp);//在fp中 拿BUFSIZE个  放到buf中
	if (retp == NULL)
		return -1;
	
	for (i = 0;i<KEY_SIZE-1&&buf[i]!= ':';i++)
		key[i] = buf[i];
	key[i] = '\0';//截获key 字符串
	i++;
	
	for(j=0;j<DESC_SIZE -1 && buf[j]!= '\0';i++,j++)
		desc[j] = buf[i];
	desc[j] = '\0';//截获desc 字符串
	return 0;
}
struct node_st *newnode(void)
{
	struct node_st *root;
	root = malloc(sizeof(*root));
	if (root == NULL)
		return NULL;
	root->desc[0] = '\0';
	int i;
	for (i = 0;i<26;i++)
	{
		root->ch[i] = NULL;
	}
	return root;
}

int insert(struct node_st **root,char *key,char *desc)
{
	if (*root== NULL)
	{
		*root = newnode();
		if (*root == NULL)
			return -1;
	}

	if (*key == '\0')
	{
		strcpy((*root)->desc,desc);
		return 0;
	}
	return insert((*root)->ch+ *key - 'a',key+1,desc);


}
char *find(struct node_st *root,char *key)
{
	if (root == NULL)//找到最底层 还没有找到
		return NULL;
	if(*key == '\0')
		return root->desc;
	return find(root->ch[*key - 'a'],key + 1);

}

int main()
{
	struct node_st *tree = NULL;
	FILE *fp;
	char desc[DESC_SIZE]= {'\0'},key[KEY_SIZE] = {'\0'};
	int ret = 0;
	fp = fopen(FNAME,"r");
	if (fp == NULL)
	{
		fprintf(stderr,"fopen():error!\n");
		exit(1);
	}

	while(1)//读取并插入
	{
		ret = get_word(fp,key,desc);
		if (ret == -1)
			break;
	/*
		puts(key);
		puts(desc);
	*/
		insert(&tree,key,desc);
	}
	char *datap;

	datap = find(tree,"donkey");
	if (datap == NULL)
		printf("can`t find!\n");
	else
		puts(datap);
	fclose(fp);
	exit(0);
}
